﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using StuMana.Services;
using System.Xml;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace StuMana.UI
{
    public partial class Cafeteria1 : Office2007Form
    {


        
        string ProPath;
        byte[] serial_buff = new byte[40];
        Services.SL025M rfid_reader = new Services.SL025M();
        Services.COM connect;
        private Bitmap image;
        private System.Windows.Forms.Timer readTimer;
        private string tag = "";
        private Boolean isSelect = false;
        private Services.student print_std = new Services.student();
        // get size of return byteArray
        private int size;


        public delegate void AsyncCallback(IAsyncResult ar);
        public delegate void AddTolstDiscoveredDevices(object o);

        private UdpState GlobalUDP;

        /// <summary>
        ///  UDP
        /// </summary>
        struct UdpState
        {
            public System.Net.IPEndPoint EP;
            public System.Net.Sockets.UdpClient UDPClient; 
             
        }




        /// Danh sách các gói tin

        List<Byte[]> liPacketUDP = new List<byte[]>();
        /// <summary>
        /// Thread Receive 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //public void ReceivePacket(IAsyncResult ar)
        public void ReceivePacket()
        {
            //MessageBox.Show("receive thread");
            if (btnStart.Text == "Stop")
            {
                while (true)
                {
                    //UdpState MyUDP = (UdpState)ar.AsyncState;
                    IPEndPoint ep;

                    try
                    {
                        //  byte[] receiveData  = MyUDP.UDPClient.EndReceive(ar, ref MyUDP.EP);
                        ep = new IPEndPoint(0, 30303);

                        //  89 = port đang lắng nghe của server 
                        byte[] receiveData = GlobalUDP.UDPClient.Receive(ref ep);
                        if (receiveData.Length > 1)
                        {
                            liPacketUDP.Add(receiveData);
                        }

                    }
                    catch (Exception e)
                    {
                        //MessageBox.Show(e.Message, "Warning12");
                        if (GlobalUDP.UDPClient.Available == 0)
                            GlobalUDP.UDPClient.Close();

                    }

                    Thread.Sleep(30);
                }
            }

        }

        /// <summary>
        /// Thread Process
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Process()
        {
            //MessageBox.Show("Process thread");
            while (true)
            {
                if (liPacketUDP.Count() > 1)
                {
                    MessageBox.Show("Process thread");

                    byte[] recData = liPacketUDP.ElementAt(1);

                   

                    liPacketUDP.RemoveAt(1);
                  
                    string ReceiveString = Encoding.ASCII.GetString(recData);
                    ReceiveString = ReceiveString.Replace("\r\n", "\n");

                    serial_buff = FromHex(ReceiveString);
                    tag = get_student_tagID().ToString();

                    grPanelCafeteria.Invoke(new AddTolstDiscoveredDevices(show_stdInfo), tag);


                  
                    MessageBox.Show("Data from Client:" + Encoding.Default.GetString(recData));
                    Thread.Sleep(30);
                }

            }



        }

        Thread thReceive;
        Thread thProcess;

        private void cmdDiscoverDevices_Click(object sender, EventArgs e)
        {
            try
            {
                // Try to send the discovery request message
                byte[] DiscoverMsg = Encoding.ASCII.GetBytes("Discovery: Who is out there?");
                
                GlobalUDP.UDPClient.Send(DiscoverMsg, DiscoverMsg.Length, new System.Net.IPEndPoint(System.Net.IPAddress.Parse("255.255.255.255"), 30303));
            }
            catch
            {
                MessageBox.Show("Unable to transmit discovery message.  Check network connectivity and ensure that no other instances of this program are running.", "Error", MessageBoxButtons.OK);
                return;
            }
        }


        public void ReceiveCallback(IAsyncResult ar)
        {
            UdpState MyUDP = (UdpState)ar.AsyncState;
            
           

            // Obtain the UDP message body and convert it to a string, with remote IP address attached as well
            if (btnStart.Text == "Stop")
            {
                try
                {
                    Byte[] receiBytes = MyUDP.UDPClient.EndReceive(ar, ref MyUDP.EP);

                    string ReceiveString = Encoding.ASCII.GetString(receiBytes);

                    liPacketUDP.Add(receiBytes);

                    MessageBox.Show(ReceiveString.ToString() + "1");



                    ReceiveString = ReceiveString.Replace("\r\n", "\n");
                    MyUDP.UDPClient.BeginReceive(ReceiveCallback, MyUDP);

                    serial_buff = FromHex(ReceiveString);
                    tag = get_student_tagID().ToString();

                    grPanelCafeteria.Invoke(new AddTolstDiscoveredDevices(show_stdInfo), tag);

                }
                catch (Exception e)
                {

                    MessageBox.Show(e.Message, "Warning 12");
                }
            }
           // show_stdInfo(tag);

        }

        public static byte[] FromHex(string hex)
        {
            hex = hex.Replace("-", "");
            byte[] raw = new byte[hex.Length / 2];
            for (int i = 0; i < raw.Length; i++)
            {
                raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
            }
            return raw;
        }
        /*--------------------------------------------------------------*/

      

        // timer event handler
        private void readTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                rfid_reader.selectCard();
                size = connect.getdata(serial_buff);
                // login
                if (serial_buff[3] != 0x01 && size != 5000 && isSelect == false)
                {
                    
                    readTimer.Enabled = false;

                    // login to tag
                    rfid_reader.LogIn();
                    size = connect.getdata(serial_buff);

                    // ReadData from tag
                    if (serial_buff[3] == 0x02 && size != 5000)
                        rfid_reader.ReadData();
                    else
                    {
                        readTimer.Enabled = true;
                        throw new Exception("Login fail");
                    }
                    size = connect.getdata(serial_buff);

                    //Receive data
                    if (serial_buff[3] == 0x00 && size != 5000)
                    {
                        tag = get_student_tagID().ToString();
                        show_stdInfo(tag);
                        isSelect = true;
                    }
                    else
                    {
                        readTimer.Enabled = true;
                        throw new Exception("Data isn't received");
                    }

                    readTimer.Enabled = true;
                }
                else if (serial_buff[3] == 0x01)
                {
                    isSelect = false;
                }
                else if (size == 5000)
                {
                }

            }
            catch (Exception es)
            {
                string msg = es.Message;
                // MessageBox.Show(es.Message,"Read Tag Fail");
            }
        }
        // change tagID into 
        private Int32 get_student_tagID()
        {

            Byte[] temp_byte = { 0x00, 0x00, 0x00, 0x00 };
            temp_byte[2] = serial_buff[6];
            temp_byte[1] = serial_buff[5];
            temp_byte[0] = serial_buff[4];
            Int32 temstr = BitConverter.ToInt32(temp_byte, 0);
            return temstr;
        }
        public void show_stdInfo(object o)
        {
            string tagID = (string)(o);
            try
            {
                if (print_std.getStdInfo(tagID))
                {
                    // change stt inout in database
                    print_std.change_stt(tagID);

                    //Insert to database the information of check in-out
                    print_std.AddNewActivity();


                    //show info to FORM
                    lblID.Text = print_std.TagID.ToString();
                    lblName.Text = print_std.Name;
                    lblClass.Text = print_std.Class;
                    lblAccount.Text = print_std.Account.ToString();
                  
                    ProPath = Environment.CurrentDirectory;
                    ProPath += "\\images\\" + lblID.Text + ".jpg";
                    image = new Bitmap(Image.FromFile(ProPath), new Size(refImage.Width, refImage.Height));
                    refImage.Image = image;
                }
                else
                    resetForm();
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                
                ProPath = Environment.CurrentDirectory;
                ProPath += "\\images\\logo.jpg";
                image = new Bitmap(Image.FromFile(ProPath), new Size(refImage.Width, refImage.Height));
                refImage.Image = image;
            }
        }

        // form reset
        private void resetForm()
        {
            lblID.Text = "None";
            lblName.Text = "None";
            lblClass.Text = "None";
            lblAccount.Text="None";
            ProPath = Environment.CurrentDirectory;
            ProPath += "\\images\\logo.jpg";
            image = new Bitmap(Image.FromFile(ProPath), new Size(refImage.Width, refImage.Height));
            refImage.Image = image;
        }
     

        // Initial COM connecting
        public void InitialConnect(StuMana.Services.COM conn)
        {
            connect = conn;
            rfid_reader.conn = conn.serialPort;
        }

    
        

        public static string ByteArrayToString(byte[] ba)
        {
            StringBuilder hex = new StringBuilder(ba.Length * 2);
            foreach (byte b in ba)
                hex.AppendFormat("{0:x2}", b);
            return hex.ToString();
        }

    


       // check in out 
        public Cafeteria1()
        {
            InitializeComponent();
        }
        private bool flag = false;
        private bool co = false;
        private Font fontForAll = null;
        private StyleManager managerStyle=new DevComponents.DotNetBar.StyleManager();



        public void ReadSetting()
        {
            XmlReader reader = XmlReader.Create("Settings.xml");
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element
                && reader.Name == "font")
                {
                    string name=reader.GetAttribute(0).ToString();
                    string style = reader.GetAttribute(1).ToString();
                    float size = float.Parse(reader.GetAttribute(2).ToString());

                    

                    if(style == "Bold")
                       fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(),size,System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if(style == "Italic")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if(style == "Regular")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(),size,System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if(style == "Strikeout")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Strikeout, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if(style == "Underline")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    
                    while (reader.NodeType != XmlNodeType.EndElement)
                    {
                        reader.Read();
                        if (reader.Name == "managerstyle" && reader.NodeType == XmlNodeType.Element)
                        {
                            reader.Read();
                            string stylemana=reader.Value.ToString();

                            if(stylemana=="Office2007Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Blue;
                            if(stylemana=="Office2007Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Silver;
                            if(stylemana=="Office2007Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Black;
                            if(stylemana=="Windows7Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Windows7Blue;
                            if(stylemana=="Office2007VistaGlass")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007VistaGlass;
                            if(stylemana=="Office2010Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Silver;
                            if(stylemana=="Office2010Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Blue;
                            if(stylemana=="Office2010Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Black;
                        }                
                    }
                } 
            }
            reader.Close();
        }

        public void ConfigSetting()
        {
            ReadSetting();
            for(int i=0;i<Controls[0].Controls.Count;i++) 
            {
                if(Controls[0].Controls[i] is LabelX)
                {
                    Controls[0].Controls[i].Font = fontForAll;
                }
            }

            styleManager1 = managerStyle;
        }
        private void LoadFoodData(int type)
        {
            ConnectionController control = new ConnectionController();
            control.connection.Open();
            try
            {
                MySql.Data.MySqlClient.MySqlCommand cmd = control.connection.CreateCommand();
                cmd.CommandText = "SELECT *  FROM Food WHERE Type = "+ type.ToString();
                MySql.Data.MySqlClient.MySqlDataAdapter adap = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adap.Fill(ds);
                dgvxDanhSachFood.DataSource = ds.Tables[0].DefaultView;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (control.connection.State == ConnectionState.Open)
                    control.connection.Clone();
            }

        }
        private void Cafeteria1_Load(object sender, EventArgs e)
        {
            cmbFoodType.SelectedIndex = 0;
            LoadFoodData(int.Parse(cmbFoodType.SelectedIndex.ToString()) + 1);
            flag = true;
            ConfigSetting();
            co = true;


            
            
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (btnStart.Text == "Start")
            {
               
                // bat goi tin nhan duoc de hien thi len information 
           
                try
                {
                    GlobalUDP.UDPClient = new UdpClient();
                    GlobalUDP.EP = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("255.255.255.255"), 30303);
                    System.Net.IPEndPoint BindEP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 30303);
     
                    GlobalUDP.UDPClient.Client.Bind(BindEP);

                    // Enable the transmission of broadcast packets without having them be received by ourself
                    GlobalUDP.UDPClient.EnableBroadcast = true;
                    GlobalUDP.UDPClient.MulticastLoopback = false;

                    // Configure ourself to receive discovery responses
                    GlobalUDP.UDPClient.BeginReceive(ReceiveCallback, GlobalUDP);
                    //// broadcast discovery 
                    thReceive = new Thread(new ThreadStart(ReceivePacket));
                    thProcess = new Thread(new ThreadStart(Process));
                   
                    //thread nhận tin bắt đầu 

                    thReceive.Start();
                    //  thread process bắt đầu
                    thProcess.Start();
                    // Transmit the discovery request message
                    //ts_label.Text = "Wifi listenning";
                    //Start.Text = "Stop";
                     btnStart.Text = "Stop";
                }
                catch
                {
                    MessageBox.Show("Unable to transmit discovery message.  Check network connectivity and ensure that no other instances of this program are running.", "Error", MessageBoxButtons.OK);
                    return;
                }
            }
            else
            {

                GlobalUDP.UDPClient.Client.Dispose();
                GlobalUDP.UDPClient.Close();
                // dừng thread nhận 
                // dừng thread xử lý 
                if (thReceive.ThreadState == ThreadState.Running)
                thReceive.Abort();
                if (thProcess.ThreadState == ThreadState.Running)
                thProcess.Abort();
             

                readTimer.Enabled = false;
            readTimer.Dispose();
               // readTimer.Stop();
                btnStart.Text="Start";
                //Start.Text = "Start";
                //ts_label.Text = "None";

                
            }
        }


        

        private void btnChoose_Click(object sender, EventArgs e)
        {
            if (lblID.Text == "lblID")
            {
                MessageBoxEx.Show("Student ID not availible", "Warning !!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }
            else
            {
                if (dgvxDanhSachFood.SelectedRows.Count > 0)
                {
                    string nameFood = " - ";
                    string idFood = " - ";
                    for (int i = 0; i < dgvxDanhSachFood.SelectedRows.Count; i++)
                    {
                        nameFood += dgvxDanhSachFood.SelectedRows[i].Cells["Name"].Value.ToString();
                        idFood += dgvxDanhSachFood.SelectedRows[i].Cells["ID"].Value.ToString();
                    }
                    
                   DialogResult diaResult=  MessageBoxEx.Show("You selected this food : " +nameFood, "Information !!!", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                   if (diaResult == DialogResult.Yes)
                   {
                       int account = int.Parse( lblAccount.Text.ToString());
                       for (int i = 0; i < dgvxDanhSachFood.SelectedRows.Count; i++)
                       {

                           int fee = int.Parse(dgvxDanhSachFood.SelectedRows[i].Cells["Price"].Value.ToString());

                           if (fee > account)
                           {
                               MessageBoxEx.Show("Ban ko du tien ", "Warning  !!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                           }
                           else
                           {
                               account = account - fee;
                               lblAccount.Text = account.ToString();
                               print_std.Account = account;
                               print_std.update_account(lblID.Text);
                           }
                       }
                    
                   }
                    // say YES => luu csdl  - tru tien vao tai khoan 
                    // say NO = > ko luu csdl 
                }
                else
                    MessageBoxEx.Show("You have not selected food", "Warning !!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
  
        
        private void btnReset_Click(object sender, EventArgs e)
        {
            lblID.Text="lblID";
            lblName.Text="lblName";
            lblAccount.Text="lblAccount";
            lblClass.Text="lblClass";
            
        }

        private void cmbFoodType_SelectedIndexChanged(object sender, EventArgs e)
        {
            flag = false;
            if(flag==false)
                LoadFoodData(int.Parse(cmbFoodType.SelectedIndex.ToString()) + 1);
            flag = true;
        }

        private void Cafeteria1_Resize(object sender, EventArgs e)
        {
            int w = dgvxDanhSachFood.Size.Width;
            int widthC = ((int)w / 4);
            if (co == true)
            {
                dgvxDanhSachFood.Columns[0].Width = widthC;
                dgvxDanhSachFood.Columns[1].Width = widthC;
                dgvxDanhSachFood.Columns[2].Width = widthC;
                dgvxDanhSachFood.Columns[3].Width = widthC;              
            }
            
        }

        private void Cafeteria1_FormClosed(object sender, FormClosedEventArgs e)
        {
            thReceive.Abort();
            thProcess.Abort();
            Application.ExitThread();
            Application.Exit();
        }

        private void Cafeteria1_FormClosing(object sender, FormClosingEventArgs e)
        {         
            thReceive.Abort();
            thProcess.Abort();
            Application.ExitThread();
            Application.Exit();
        }

  
       

    

       

        
      

        


    
    }
}
